package com.csy.user.controller.system;

import com.csy.commons.constant.UserConstants;
import com.csy.commons.core.controller.BaseController;
import com.csy.commons.core.domain.BaseResponse;
import com.csy.commons.core.page.PageResult;
import com.csy.commons.core.utils.ChainedMap;
import com.csy.commons.core.utils.SecurityUtils;
import com.csy.commons.dto.SysRole;
import com.csy.commons.dto.SysUser;
import com.csy.commons.framework.service.SysRoleService;
import com.csy.user.entity.system.service.SysPostService;
import com.csy.user.entity.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysRoleService roleService;

	@Autowired
	private SysPostService postService;

	/**
	 * 查询用户列表
	 * 
	 * @param user
	 * @return
	 */
	@GetMapping("/list")
	public PageResult list(SysUser user) {
		startPage();
		List<SysUser> list = userService.selectUserList(user);
		System.out.println("getNickName----" + user.getNickName());
		return getData(list);

	}

	/**
	 * 查看用户个人信息
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping("/profile")
	public BaseResponse<SysUser> getuserProfile(@RequestBody String username) {
		SysUser sysUser = userService.selectUserByUserName(username);
		return BaseResponse.success(sysUser);

	}

	/**
	 * 更新密码
	 * 
	 * @param username
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@RequestMapping("/profile/updatePwd")
	public BaseResponse<String> updatePwd(String username, String oldPassword, String newPassword) {
		String status = userService.updatePwd(username, oldPassword, newPassword);

		if (status.equals("401")) {
			return BaseResponse.fail("旧密码不正确，修改失败");
		}

		return BaseResponse.success("修改成功");

	}

	/*
	 * 删除用户
	 */
	@DeleteMapping("/{userIds}")
	public BaseResponse<Integer> remove(@PathVariable Long[] userIds) {
		return toAjax(userService.deleteUserByIds(userIds));
	}

	/*
	 * 重置密码
	 */
	@PutMapping("/resetPwd")
	public BaseResponse<Integer> resetPwd(@RequestBody SysUser user) {
		// 校验用户是否是admin
		userService.checkUserAllowed(user);
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
		user.setUpdateBy(SecurityUtils.getUserName());
		return toAjax(userService.resetPwd(user));

	}

	/*
	 * 状态修改
	 */
	@PutMapping("/changeStatus")
	public BaseResponse<Integer> changeStatus(@RequestBody SysUser user) {
		userService.checkUserAllowed(user);
		user.setUpdateBy(SecurityUtils.getUserName());
		return toAjax(userService.updateUserStatus(user));
	}

	@GetMapping(value = { "/", "/{userId}" })
	public ChainedMap getInfo(@PathVariable(value = "userId", required = false) Long userId) {

		ChainedMap map = ChainedMap.create().set("code", 200).set("msg", "操作成功");

		// 获取角色列表
		List<SysRole> roleList = roleService.selectRoleAll();

		// 封装用户关联角色信息
		if (SysUser.isAdmin(userId)) {
			map.put("roles", roleList);
		} else {
			List<SysRole> cList = roleList.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList());
			map.put("roles", cList);
		}

		// 用户管理部门
		map.put("posts", postService.selectPostAll());

		// 如果是修改操作
		if (!Objects.isNull(userId)) {
			map.put("data", userService.selectUserById(userId));
			map.put("postIds", postService.selectPostListByUserId(userId));
			map.put("roleIds", roleService.selectRoleListByUserId(userId));
		}
		return map;
	}

	/*
	 * 新增用户
	 */
	@PostMapping
	public BaseResponse<Integer> add(@RequestBody SysUser user) {

		if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
			return BaseResponse.fail("新增用户'" + user.getUserName() + "'失败，登录账号已经存在");
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return BaseResponse.fail("新增用户'" + user.getUserName() + "'失败，手机号码已经存在");
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return BaseResponse.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已经存在");
		}
		user.setCreateBy(SecurityUtils.getUserName());
		user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

		return toAjax(userService.insertUser(user));
	}

	/*
	 * 修改用户
	 */
	@PutMapping
	public BaseResponse<Integer> edit(@RequestBody SysUser user) {

		// 校验用户是否允许操作
		userService.checkUserAllowed(user);

		if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
			return BaseResponse.fail("修改用户'" + user.getUserName() + "'失败，手机号码已经存在");
		} else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
			return BaseResponse.fail("修改用户'" + user.getUserName() + "'失败，邮箱账号已经存在");
		}
		user.setUpdateBy(SecurityUtils.getUserName());

		return toAjax(userService.updateUser(user));
	}
	
	/**
	 * 查询用户信息
	 * 
	 * @param nickName
	 * @return
	 */
	@RequestMapping("/getByName")
	public SysUser getByName(@RequestParam("nickName") String nickName) {
		return userService.getByName(nickName);
	}
	
	/**
	 * 查询用户信息
	 * 
	 * @param username
	 * @return
	 */
	@GetMapping("/getByUsername")
	public SysUser getByUsername(@RequestParam("username") String username) {
		return userService.getByUsername(username);
	}

}